package com.glela.activ.dao.impl;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.glela.activ.dao.OActivConditionSalesAmountDao;
import com.glela.activ.dao.OActivDao;
import com.glela.activ.mapper.OActivMapper;
import com.glela.activ.model.OActiv;
import com.glela.activ.service.domain.info.OActivInfoConditionSaleAmountVo;
import com.glela.activ.service.domain.info.OActivInfoVo;

@Repository
public class OActivDaoImpl implements OActivDao {
	private static Logger LOGGER = LoggerFactory.getLogger(OActivDaoImpl.class);

	@Autowired
	private OActivMapper					oActivMapper;
	@Autowired
	private OActivConditionSalesAmountDao	oActivConditionSalesAmountDao;

	@Override
	public OActiv queryByProductId(long productId, String activTime) {
		try {
			return oActivMapper.selectByProductId(productId, activTime);
		} catch (Exception e) {
			LOGGER.error("订单活动货品{}在时间{}点设置有异常:{}", productId, activTime, e.getMessage());
			throw new NullPointerException("活动设置异常");
		}
	}

	@Override
	public OActiv queryById(long activId) {
		return oActivMapper.selectByPrimaryKey(activId);
	}

	@Override
	public OActivInfoVo queryInfoById(long activId) {
		OActiv checkActiv = queryById(activId);
		if (checkActiv == null) {
			return null;
		}
		OActivInfoVo oActivInfoVo = new OActivInfoVo();
		oActivInfoVo.setActivId(checkActiv.getId());
		oActivInfoVo.setActivType(checkActiv.getActivType());
		//根据类型封装活动实体信息
		switch (checkActiv.getActivType()) {
			case 1://普通优惠
				List<OActivInfoConditionSaleAmountVo> checkConditions1 = oActivConditionSalesAmountDao.selectByActivId(activId);
				if (CollectionUtils.isEmpty(checkConditions1)) {
					LOGGER.error("活动{}类型1【普通优惠】没有限制条件", activId);
					throw new NullPointerException("活动规则异常");
				} else if (checkConditions1.size() > 1) {
					LOGGER.error("活动{}类型1【普通优惠】有{}个限制条件", activId, checkConditions1.size());
					throw new NullPointerException("活动规则异常");
				}
				oActivInfoVo.getConditions().getConditionSalesAmount().addAll(checkConditions1);
				break;
			case 2://多级优惠
				List<OActivInfoConditionSaleAmountVo> checkConditions2 = oActivConditionSalesAmountDao.selectByActivId(activId);
				if (CollectionUtils.isEmpty(checkConditions2)) {
					LOGGER.error("活动{}类型2【多级优惠】没有限制条件", activId);
					throw new NullPointerException("活动规则异常");
				}
				oActivInfoVo.getConditions().getConditionSalesAmount().addAll(checkConditions2);
				break;

			default:
				oActivInfoVo = null;
				LOGGER.warn("活动类型[{}]未实现", checkActiv.getActivType());
				break;
		}
		return oActivInfoVo;
	}
}